<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2019/3/9
 * Time: 16:55
 */

namespace app\admin\controller;

use app\admin\model\Mch as MchModel;
use app\admin\model\MchWithdraw;
use app\index\validate\Mch as MchValidate;
use Naixiaoxin\ThinkWechat\Facade;
use think\db\Where;
use think\facade\Session;

class Mch extends Base {
    protected static $payment;
    public function __construct()
    {
        parent::__construct();
        $this->model = new MchModel;
        $this->validate = new MchValidate;
        self::$payment = Facade::payment();
    }

    public function index($limit=10,$page=1){
        $where = [];
        if (self::$mc_id) {
            $where['mc_id']=self::$mc_id;
        }
        $data = request()->post();
        if($data){
            if($data['name']){
                $where[]=['think_mch.name','like','%'.trim($data['name']).'%'];
            }
            if($data['company']){
                $where[]=['think_mch.company','like','%'.trim($data['company']).'%'];
            }
            if($data['status']){
                $where['think_mch.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where[]= ['think_mch.create_time','between time',[$start,$end]];
            }
        }

        $list = $this->model->getList($where,$limit);
        if(request()->isAjax()){
            return $this->__s($this->model->getLastSql(),$list);
        }else{
            $this->assign('total',$list->total());
            $this->assign('list',$list);
            return view();
        }
    }

    public function add($id=0){
        if($id){
            $info = $this->model->find($id);
            $this->assign('info',$info);
        }
        return view();
    }


    /**
     * 文章操作
     */
    public function insert(){
        $data = request()->param();
        if(!$this->validate->check($data)){
            $this->__e($this->validate->getError());
        }
        if(!$data['id']){
            unset($data['id']);
            $data['create_time']=time();
            if(!$this->model->insert($data)){
                $this->__e('添加失败');
            }
            $this->__s('添加成功',['redirect'=>Url('article/index')]);
        }else{
            $data['update_time']=time();
            if(!$this->model->isUpdate(true)->save($data)){
                $this->__e('修改失败');
            }
            $this->__s('修改成功',['redirect'=>Url('mch/index')]);
        }
    }

    /**
     * ba59abbe56e057f20f88  //6ba0a8c7
     * @param int $id
     */
    public function reset($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        $mch = $this->model->get($id);
        if(!$mch){
            $this->__e('商户不存在');
        }
        $pwd =  PseudoRandom::hex();
        $mch->password = self::_password($pwd);
        if(!$mch->isUpdate(true)->save()){
            $this->__e('重置密码失败');
        }
        $this->__s('重置密码成功,重置之后的密码是:'.$pwd);
    }

    public function status($id=0,$status=0){
        if(!$id || !$status){
            $this->__e('缺少参数');
        }
        $mch = $this->model->get($id);
        if(!$mch){
            $this->__e('商户不存在');
        }
        if($status==2){
            $mch->cross_time = time();
        }
        $mch->status = $status;
        if(!$mch->isUpdate(true)->save()){
            $this->__e('操作失败');
        }
        $this->__s('操作成功');
    }


    /**
     * 删除
     * @param int $id
     * @throws \Exception
     */
    public function del($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        if(!$this->model->where('id','eq',$id)->delete()){
            $this->__e('删除失败');
        }
        $this->__s('删除成功');
    }

    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myself(){
        $mch = new \app\admin\model\Mch();
        $mch = $mch->get(session('_id'));
        $rechage = new \app\admin\model\Rechange();
        $list = $rechage->getListByMcId($mch['id']);
        $this->assign('user',$mch);
        $this->assign('list',$list);
        return view();
    }

    /**
     * @param string $title
     * @param int $fee
     * @param int $type
     * @return \think\Response|\think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function rechage($title='',$fee=0){
        if(!$title){
            return json(['code'=>1,'msg'=>'请填写订单主题']);
        }
        if(!$fee){
            return json(['code'=>1,'msg'=>'请填写订单金额']);
        }
        $uid = session('mc_id');
        $_data = $order = [
            'body' => $title,
            'out_trade_no' => build_order_no(),
            'total_fee' => $fee * 100,
            'trade_type' => 'NATIVE'
        ];
        $_data['create_time']=time();
        $_data['title']=$title;
        $_data['total_fee'] = $fee;
        $_data['mc_id'] = $uid;
        $_data['type'] = 2;
        unset($_data['body']);
        $rechage = new \app\admin\model\Rechange();
        if(!$rechage->insert($_data)){
            return $this->__e('订单创建失败,请稍后再试');
        }
        $result = self::$payment->order->unify($order);
        return json(['status'=>1,'data'=>$result['code_url'],
            'out_trade_no'=>$_data['out_trade_no']]);
    }

    /**
     * @param string $out_trade_no
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function query_order($out_trade_no=''){
        if(!$out_trade_no){
            return json(['code'=>1,'msg'=>'请填写查询单号']);
        }
        $rechage = new \app\admin\model\Rechange();
        $order = $rechage
            ->where('out_trade_no','eq',$out_trade_no)
            ->find();
        if(!$order){
            return json(['code'=>1,'msg'=>'查询订单不存在']);
        }
        $result = self::$payment->order
            ->queryByOutTradeNumber($out_trade_no);
        if($result['trade_state']=='SUCCESS' && $result['result_code']=='SUCCESS'){
            $rechage->where('id','eq',$order['id'])
                ->update([
                    'id'=> $order['id'],
                    'payment_trade_no'=>$result['transaction_id'],
                    'finish_time'=>time(),
                    'payment_notify_time'=>$result['time_end'],
                    'payment_trade_status'=>$result['trade_state_desc'],
                    'status'=>2
                ]);
            $mch = new \app\admin\model\Mch();
            $mch->where('id','eq',$order['mc_id'])->update([
                'money'=> $order['total_fee'] * (1-0.006)
            ]);
            return json(['code'=>0,'msg'=>'支付成功']);
        }else{
            return json(['code'=>1,'msg'=>'']);
        }
    }

    /**
     * @param int $limit
     * @param int $page
     * @return \think\Response|\think\response\View
     * @throws \think\exception\DbException
     */
    public function withdraw($limit=10,$page=1){
        $where = new Where();
        $model = new MchWithdraw();
        $model_name = $model->getTable();
        $data = request()->post();
        $where[$model_name.'.status']=['neq',-1];
        if(self::$mc_id){
            $where[$model_name.'.mc_id']=self::$mc_id;
        }
        if($data){
            if($data['proxy']){
                $list = $this->model
                    ->whereLike('name',"%{$data['proxy']}%")
                    ->select();
                $ids = [];
                foreach ($list as $v){
                    array_push($ids,$v['id']);
                }
                $where[$model_name.'.mc_id']=['in',$ids];
            }
            if($data['name']){
                $where[$model_name.'.name']=['like','%'.trim($data['name']).'%'];
            }
            if($data['status']){
                $where[$model_name.'.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where[$model_name.'.create_time']= ['between time',[$start,$end]];
            }
        }
        $list = $model->getList($where,$limit);
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else{
            $this->assign('total',$list->total());
            $this->assign('list',$list);
            return view();
        }
    }

    /**
     * @param int $id
     * @return \think\response\View
     */
    public function check_withdraw($id=0){
        $model = new MchWithdraw();
        $info = $model->find($id);
        $mch = $this->model->get(self::$mc_id);
        $this->assign('info',$info);
        $this->assign('mch',$mch);
        return view();
    }

    /**
     * 删除商户提现
     * @param int $id
     * @return \think\Response
     */
    public function del_withdraw($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        $model = new MchWithdraw();
        $info = $model->get($id);
        if(!$info){
           return $this->__e('申请不存在');
        }
        $info->status = -1;
        if(!$info->save()){
           return $this->__e('删除失败');
        }
        return $this->__s('删除成功');
    }
    /**
     * 确认提现
     * @param int $id
     * @param int $status
     * @param string $info
     * @return \think\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function update_withdraw($id=0,$status=3,$info=''){
        if($id){
            $model = new MchWithdraw();
            $_info = $model->get($id);
            if(!$_info){
                return $this->__e('申请不存在');
            }
            if($_info['status']!=1){
                return $this->__e('申请已处理');
            }
            if($status==3){
                $_info->status = 3;
                $_info->fail_info = $info;
                $_info->update_time = time();
                if(!$_info->save()){
                    return $this->__e('操作失败');
                }
                return $this->__s('操作成功',['redirect'=>Url('mch/withdraw')]);
            }else{
                $open_id = $this->model->getOpenIdByMid($_info['mc_id']);
                if(!$open_id){
                    return $this->__e('提现失败，OpenId不存在');
                }
                $this->redpack($_info['order_id'],$open_id,$_info['money'],'',$out);
                if($out['status']==2){
                    $_proxy = $this->model->get($_info['mc_id']);
                    $_proxy->money = $_proxy['money'] - $_info['money'];
                    $_proxy->save();
                }
                $_info->status = $out['status'];
                $_info->set_info = $out['set_info'];
                if(!$_info->save()){
                    return $this->__e('操作失败');
                }
                return $this->__s('操作成功',['redirect'=>Url('mch/withdraw')]);
            }
        }else{
            $data = request()->post();
            $model = new MchWithdraw();
            $result = $model
                ->addNew('',$data['money'],self::$mc_id,$out);
            if(!$result){
                return $this->__e($out);
            }
            if(!$result->save()){
                return $this->__e('申请失败');
            }
            return $this->__s('申请成功等待审核',['redirect'=>Url('mch/withdraw')]);
        }
    }

    /**
     * @param string $order_id
     * @param string $open_id
     * @param int $money
     * @param string $remark
     * @param null $out
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function redpack($order_id='',$open_id='',$money=0,$remark='',&$out=null){
        $redpackData = [
            'mch_billno'   => $order_id,
            'scene_id'     => 'PRODUCT_5',
            'send_name'    => '天空文化传播',
            're_openid'    => $open_id,
            'total_num'    => 1,
            'total_amount' => $money * 100,
            'wishing'      => '商户提现',
            'act_name'     => '天空文化传播',
            'remark'       => $remark?$remark:'商户提现',
        ];
        $result = self::$payment->redpack->sendNormal($redpackData);
        if($result['return_code']!='SUCCESS'){
            $out = [
                'status'=>4,
                'set_info'=> '微信红包发送异常'
            ];
        }
        if($result['err_code']=='SENDNUM_LIMIT'
            || $result['err_code']=='NO_AUTH'){
            $out = [
                'status'=>4,
                'set_info'=> $result['return_msg']
            ];
        }
        if($result['err_code']=='SEND_FAILED'){
            $out = [
                'status'=>3,
                'set_info'=> $result['return_msg']
            ];
        }
        if($result['err_code']=='SYSTEMERROR'){
            self::$payment->redpack->sendNormal($redpackData);
        }
        if($result['result_code']=='SUCCESS'){
            $out = [
                'status'=>2,
                'set_info'=> $result['return_msg']
            ];
        }
    }

    /**
     * 修改密码
     * @param string $pwd
     * @return \think\Response
     */
    public function change_pwd($pwd=''){
        if(!$pwd){
            $this->__e('缺少参数');
        }
        $mch = $this->model->get(self::$mc_id);
        if(!$mch){
            return $this->__json(1,'商户不存在');
        }
        $mch->password = self::_password($pwd);
        $mch->update_time= time();
        if(!$mch->save()){
            return $this->__e('修改失败');
        }
        Session::clear();
        return $this->__s('修改成功');
    }
}